package com.bizmda.bizsip.app.executor;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.app.api.AppBeanInterface;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.bizsip.common.BizResultEnum;
import com.bizmda.bizsip.common.BizUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class AppBeanAppExecutor extends AbstractAppExecutor {
    private AppBeanInterface appBeanService = null;
    private Class clazz;

    public AppBeanAppExecutor(String serviceId, String type, Map configMap,boolean isAppYml) {
        super(serviceId, type, configMap);
        String className = (String)(isAppYml?
                configMap.get("class-name"):configMap.get("className"));
        try {
            log.info("初始化app-bean-service类App服务[{}]关联类: {}",serviceId,className);
            this.clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            log.error("创建"+className+"类失败！",e);
            return;
        }

    }

    @Override
    public void init() {
        // 没有初始化内容
    }

    @Override
    public BizMessage<JSONObject> doAppService(BizMessage<JSONObject> bizMessage) throws BizException {
        log.debug("调用app-bean-service类App服务:\n{}",BizUtils.buildBizMessageLog(bizMessage));
        if (this.appBeanService == null) {
            Object object = SpringUtil.getBean(clazz);
            if (object instanceof AppBeanInterface) {
                this.appBeanService = (AppBeanInterface)object;
            }
            else {
                throw new BizException(BizResultEnum.OTHER_ERROR,"类["+this.clazz.getName()+"]不是AppBeanInterface接口实现类，创建BizService服务失败");
            }
        }
        log.debug("调用app-bean-service相关类:{}",this.appBeanService.getClass().getName());
        JSONObject jsonObject = this.appBeanService.process(bizMessage.getData());
        log.debug("app-bean-service类App服务返回:\n{}",BizUtils.buildJsonLog(jsonObject));
        return BizMessage.buildSuccessMessage(bizMessage,jsonObject);
    }
}
